<?php

namespace App\Http\Controllers\Guard\Login;

use App\Http\Controllers\Common\GuardController;
use App\Models\Common\China;
use App\Models\Flight\FlightInfo;
use App\Models\Flight\Order;
use App\Models\Rbac\GuardUser;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;
use Kkokk\Poster\PosterManager;

class LoginController extends GuardController
{

    public function getPDF(Request $request){
        $code = $request->input('code','H812NV');
        $records = Order::query()->where(['code'=>$code,'is_hide'=>0])->with('getFlightInfo')->get();
        $firstRecord = $records->first();
        $createdAt = Carbon::parse(date('Y-m-d',strtotime($firstRecord->created_at)))->format('D j M Y');
        $isDouble = $firstRecord->is_double;
        $flightInfos = [];
        $passengers = [];
        $extra = [];
        $flight = FlightInfo::query()->where('id',$firstRecord->flight_id)->first();
        $during = Carbon::parse($flight->start_fly_time)->diffInMinutes(Carbon::parse($flight->end_fly_time));
        //=============================== 航班 ===========================================================
        $flightInfos[] = [
            'date'=>Carbon::parse($flight->date)->format('l j F Y'),
            'flight_no'=>$flight->flight_no,
            'simple_start_airport'=>$flight->start_airport,
            'simple_end_airport'=>$flight->end_airport,
            'full_start_airport'=>getFullAirport($flight->start_airport),
            'full_end_airport'=>getFullAirport($flight->end_airport),
            'start_airport'=>getAirport($flight->start_airport),
            'end_airport'=>getAirport($flight->end_airport),
            'start_fly_time'=>$flight->start_fly_time,
            'end_fly_time'=>$flight->end_fly_time,
            'during'=>toHumanHours($during)
        ];
        //往返航班
        if($isDouble==1){
            $coupleFlight = FlightInfo::query()->where('id',$firstRecord->couple_flight_id)->first();
            $during = Carbon::parse($coupleFlight->start_fly_time)->diffInMinutes(Carbon::parse($coupleFlight->end_fly_time));
            $flightInfos[] = [
                'date'=>Carbon::parse($coupleFlight->date)->format('l j F Y'),
                'flight_no'=>$coupleFlight->flight_no,
                'simple_start_airport'=>$coupleFlight->start_airport,
                'simple_end_airport'=>$coupleFlight->end_airport,
                'full_start_airport'=>getFullAirport($coupleFlight->start_airport),
                'full_end_airport'=>getFullAirport($coupleFlight->end_airport),
                'start_airport'=>getAirport($coupleFlight->start_airport),
                'end_airport'=>getAirport($coupleFlight->end_airport),
                'start_fly_time'=>$coupleFlight->start_fly_time,
                'end_fly_time'=>$coupleFlight->end_fly_time,
                'during'=>toHumanHours($during)
            ];
        }
        //=============================== 乘客 ===========================================================
        foreach ($records as $record) {
            //dump($record);
            $passengers[] = [
                'sub_name'=>getSubName($record->name),
                'name'=>implode(' ', array_reverse(explode(' ', $record->name))),
                'type'=>getPassengerTypeForEnglish($record->passenger_type,$record->passenger_sex),
            ];
        }
        //=============================== Extra services ===========================================================
        $strContent = $this->qrCode($code);

        $text = $strContent;
        $imgName = time().uniqid().'.png';
        $subPath = "qr/$imgName";
        $absPath = public_path($subPath);
        PosterManager::Poster()->Qr($text,$absPath);

        $imageData = file_get_contents($absPath);
        $img64 = base64_encode($imageData);


        return view('order',compact('firstRecord','isDouble','createdAt','flightInfos','passengers','img64'));
    }

    public function qrCode($code){

        $orders = Order::where(['code'=>$code])->where('is_hide',0)->get();
        $flight = FlightInfo::query()->where('id',$orders->first()->flight_id)->first();
        $coupleFlight = FlightInfo::query()->where('id',$orders->first()->couple_flight_id)->first();


        $strContent = $orders->first()->code." ";
        foreach ($orders as $order){
            $gender = $order->passenger_sex=='M'?"Mr":"Miss";
            $strContent .= "$gender $order->name";
        }

        $strContent.="$flight->flight_no $coupleFlight->flight_no";
        return $strContent;
    }


    public function toHumanHours($during){
        $hour = floor($during/60);
        $min = $during-$hour*60;
        return "$hour h : $min m";
    }

    public function getSubName($name){
        $sub = '';
        $subNames= explode(' ',$name);
        foreach ($subNames as $subName) {
            $sub .=Str::substr($subName, 0,1);
        }
        return $sub;
    }


    public function login(Request $request) {

        $from = $request->header('from','guard');
        $adminUserName = $request->input('adminUserName');
        $password = $request->input('password');
        $adminUser = (new GuardUser())->getAdminUserByNameAndPwd($adminUserName,md5($password));
        if(!empty($adminUser)){
            $adminUser->token = createNewToken($adminUser->id,$from);
            if(env('IS_WRITE_LOGIN_LOG',false))
                $adminUser->addLoginLog($request->ip(),getOS(),getBrowser());

            if(env('IS_USE_REDIS',false)){
                $key = "token:$from:$adminUser->token";
                if(!Redis::exists($key)){
                    Redis::setex("token:$from",env('TOKEN_LIFE_TIME',120),$adminUser->token);
                }
            }

            return responseSuccess($adminUser->toArray(),1,200000);
        }else{
            return responseFail(200001);
        }
    }

    public function logout(Request $request) {
        $from = $request->header('from');
        $token = $request->header('token');

        if(env('IS_USE_REDIS',false)){
            $key = "token:$from:$token";
            if(Redis::exists($key)){
                Redis::del($key);
            }
        }

        return responseSuccess([],0,200002);
    }

    public function getVerifyCodeImg(Request $request) {
        $w = $request->input('w',150);
        $h = $request->input('h',50);
        $builder  = new CaptchaBuilder();
        $builder->build($w,$h);
        $phrase = $builder->getPhrase();//获取验证码内容
        $request->session()->put('verifyCode',$phrase);
        ob_clean();
        return response($builder->output())->header('Content-type','image/jpeg');
    }

    public function getArea(Request $request) {
        $records = China::where('pcode',0)->with('children')->get();
        $this->handleChildren($records);
        return responseSuccess($records->toArray());
    }
}
